<?php

namespace app\controllers;

use Yii;
use Faker\Provider\Uuid;
use yii\web\Controller;
use app\common\Dictionary;
use app\models\TBaseSchool;
use app\models\TBaseDepartment;
use app\common\ArrayHelper;
use app\models\TBaseUserProfile;
use app\models\TBaseSmsLog;
use app\models\TBaseUser;
use app\models\TBaseMajor;
use app\models\TBaseClassMember;

class UserController extends Controller{
    public $enableCsrfValidation = false;
    const API_URL = 'http://smsapi.c123.cn/OpenPlatform/OpenApi'; //短信发送接口地址
    const APIUrl = 'http://hy.mix2.zthysms.com/sendSms.do'; //短信发送接口地址
    const SMS_LIMIT_HOUR = 5; //同一手机号每小时允许发送3次短信
    const SMS_LIMIT_DAY = 20; //同一手机号每天允许发送10次短信
    const timeout = 30; //超时设置
    const FILE_DELETE_SUCCESS = 1;
    const FILE_DELETE_FAIL = 0;
    const FILE_NO_EXISTS = -1;
    public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /*
 * 微信小程序获取openid
 * gyq
 * 2020/4/14
 * */
    public function actionGetOpenId(){
        $code=isset($_REQUEST['code']) ? $_REQUEST['code'] : $error[]='code不能为空';
        if(!empty($error)){
            $result=[
                'msg'=>'缺少请求参数',
                "ver"=> "1.5.0",
                'type'=>'4.0',
                'data'=>$error,
                'code'=>'601'
            ];
        }else{
            $url='https://api.weixin.qq.com/sns/jscode2session';
            $data=[
                'appid'=>'wx8f5449c67f032fa7' ,
                'secret'=>'ef096ac252739d43752dc6084996d427' ,
                'js_code'=>$code ,
                'grant_type'=>'authorization_code' ,
            ];
            $info=self::hGet($url,$data);
            $result = [
                'msg' => '查找成功',
                'ver' => '1.5.0',
                'data' => $info,
                'success' => true,
                'code' => 200,
            ];
        }
        \yii::$app->end(json_encode($result));
    }
    /*
     * 微信小程序账号密码登录
     * gyq
     * 2019/12/11
     * */
    public function  actionLogin(){
        $username=isset($_REQUEST['username'])&&!empty($_REQUEST['username']) ? $_REQUEST['username'] : $error[]='用户名不能为空';
        $password=isset($_REQUEST['password'])&&$_REQUEST['password'] ? $_REQUEST['password'] : $error[]='密码不能为空';
        $userType = isset($_REQUEST['userType']) && !empty($_REQUEST['userType']) ? $_REQUEST['userType'] : $error = array('角色类型不能为空');
        $openid=isset($_REQUEST['openid']) ? $_REQUEST['openid'] : $error[]='openid不能为空';
        if(!empty($error)){
            $result=[
                'msg'=>'缺少请求参数',
                "ver"=> "1.5.0",
                'type'=>'4.0',
                'data'=>$error,
                'code'=>'601'
            ];
            \yii::$app->end(json_encode($result));
        }else{
            //1.验证用户是否存在
            $sql="select * from t_base_user where username=:username and del_flag=0";
            $userInfo=\yii::$app->db->createCommand($sql)->bindValues([':username'=>$username])->queryOne();
            if(empty($userInfo)){
                $sql="select * from t_base_user_profile where del_flag=0 and mobilephone=:mobilephone";
                $res=\yii::$app->db->createCommand($sql)->bindValues([':mobilephone'=>$username])->queryOne();
                if(empty($res)){
                    $result=[
                        'msg'=>'账号不存在',
                        "ver"=> "1.5.0",
                        'type'=>'4.0',
                        'data'=>['账号不存在'],
                        'code'=>'404'
                    ];
                    \yii::$app->end(json_encode($result));
                }else{
                    $sql="select * from t_base_user where del_flag=0 and id=:id";
                    $userInfo=\yii::$app->db->createCommand($sql)->bindValues([':id'=>$res['user_id']])->queryOne();
                }
            }
            if(empty($userInfo)){
                $result=[
                    'msg'=>'账号不存在',
                    "ver"=> "1.5.0",
                    'type'=>'4.0',
                    'data'=>['账号不存在'],
                    'code'=>'404'
                ];
                \yii::$app->end(json_encode($result));
            }
            //2.验证密码是否正确
            if($userInfo['password']!=md5($password.$userInfo['salt'])){
                $result = [
                    "msg" => "账号或密码错误",
                    "ver" => "1.5.0",
                    'type'=>'4.0',
                    'data' =>['账号或密码错误'],
                    'code' => '400'
                ];
                \yii::$app->end(json_encode($result));
            }else{
                //判断登录端类型
                $sql="select type from t_base_user_profile where user_id=:userId and del_flag=0";
                $type=\yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userInfo['id']])->queryScalar();
                if($userType=='userType.student'){
                    //学生端登录
                    if(!in_array($type,['userType.student','userType.society','userType.company'])){
                        $result = [
                            "msg" => "您目前账号是教师身份，请前往“微知库教师版”小程序登录",
                            "ver" => "1.5.0",
                            'type'=>'4.0',
                            'data' =>['您目前账号是教师身份，请前往“微知库教师版”小程序登录'],
                            'code' => '400'
                        ];
                        \yii::$app->end(json_encode($result));
                    }
                }else{
                    //教师端登录
                    if($type!='userType.teacher'){
                        $role="学生";
                        if($type=='userType.student'){
                            $role="学生";
                        }else if($type=='userType.society'){
                            $role="社会学习者";
                        }else if($type=='userType.company'){
                            $role="企业";
                        }
                        $msg="您目前账号是".$role."身份，请前往“微知库学生版”小程序登录";
                        $result = [
                            "msg" =>$msg ,
                            "ver" => "1.5.0",
                            'type'=>'4.0',
                            'data' =>[$msg],
                            'code' => '400'
                        ];
                        \yii::$app->end(json_encode($result));
                    }
                }
                    $this->AppUserInfo($userInfo['id'],$openid);
            }
        }
    }
    /**
     * 微信小程序手机验证码登陆
     * gyq
     * 2019/12/26
     */
    public function actionAppMobileLogin() {
        $error      = array();
        $phone      = isset($_REQUEST['phone']) && !empty($_REQUEST['phone']) ? $_REQUEST['phone'] : $error = array('手机号不能为空');
        $userType = isset($_REQUEST['userType']) && !empty($_REQUEST['userType']) ? $_REQUEST['userType'] : $error = array('角色类型不能为空');
        $phoneCode  = isset($_REQUEST['code']) && !empty($_REQUEST['code']) ? $_REQUEST['code'] : $error = array('手机验证码不能为空');
        $openid=isset($_REQUEST['openid']) ? $_REQUEST['openid'] : $error[]='openid不能为空';
        $type = "sendMsgBusinessType.singin";
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $checkCode = $this->CheckSms($phone, $phoneCode, $type);
            if ($checkCode) {
                //根据手机号返回用户id
                $profile = TBaseUserProfile::find()->where('mobilephone=:phone and del_flag=0', [':phone' => $phone])->one();
                if ($profile) {
                    if($userType=='userType.student'){
                        //学生端登录
                        if(!in_array($profile['type'],['userType.student','userType.society','userType.company'])){
                            $result = [
                                "msg" => "您目前账号是教师身份，请前往“微知库教师版”小程序登录",
                                "ver" => "1.5.0",
                                'type'=>'4.0',
                                'data' =>['您目前账号是教师身份，请前往“微知库教师版”小程序登录'],
                                'code' => '400'
                            ];
                            \yii::$app->end(json_encode($result));
                        }
                    }else{
                        //教师端登录
                        if($profile['type']!='userType.teacher'){
                            $role="学生";
                            if($profile['type']=='userType.student'){
                                $role="学生";
                            }else if($profile['type']=='userType.society'){
                                $role="社会学习者";
                            }else if($profile['type']=='userType.company'){
                                $role="企业";
                            }
                            $msg="您目前账号是".$role."身份，请前往“微知库学生版”小程序登录";
                            $result = [
                                "msg" =>$msg,
                                "ver" => "1.5.0",
                                'type'=>'4.0',
                                'data' =>[$msg],
                                'code' => '400'
                            ];
                            \yii::$app->end(json_encode($result));
                        }
                    }
                    $this->AppUserInfo($profile->user_id,$openid);
                } else {
                    $result = array(
                        "msg" => "该用户尚未注册!",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '400'
                    );
                    Yii::$app->end(json_encode($result));
                }
            } else {
                $result = array(
                    "msg" => "手机号或验证码错误",
                    "ver" => "1.5.0",
                    'data' => ['手机号或验证码错误'],
                    'code' => '400'
                );
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /**
     * 微信小程序学员信息接口
     * @param int  userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppGetXmProfile()
    {
        $error = array();
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $this->AppUserInfo($userId,'');
        }
    }
    /**
     * 微信小程序学员修改个人信息接口
     * @param int  userId:用户ID mobilephone:手机号  projectId:联盟ID
     * @param int   school_id:学校ID major_id:专业ID student_no:学号
     * @param string  pet_name:姓名 gender:性别 email:邮箱 type:角色
     * @param string  province:省 city:市 address:详细地址 birthday:生日  //教师端传的字段（不是必传字段）
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppUpdateXmProfile()
    {
        $error = array();
        $userId = !empty($_REQUEST['uid'])?$_REQUEST['uid']:$error=array('用户id不能为空');
        $pet_name = !empty($_REQUEST['pet_name'])?$_REQUEST['pet_name']:$error=array('姓名不能为空');
        $gender = !empty($_REQUEST['gender'])?$_REQUEST['gender']:$error=array('性别不能为空');
        $mobilephone = !empty($_REQUEST['mobilephone'])?$_REQUEST['mobilephone']:'';
        $email = !empty($_REQUEST['email'])?$_REQUEST['email']:'';
        $type = !empty($_REQUEST['type'])?$_REQUEST['type']:$error=array('角色不能为空');
        $school_id = !empty($_REQUEST['school_id'])?$_REQUEST['school_id']:$error=array('学校不能为空');
        $major_id = !empty($_REQUEST['major_id'])?$_REQUEST['major_id']:$error=array('专业不能为空');
        $project_id = !empty($_REQUEST['project_id'])?$_REQUEST['project_id']:'';
        $studentType = !empty($_REQUEST['studentType'])?$_REQUEST['studentType']:'';
        $student_no = !empty($_REQUEST['student_no'])?$_REQUEST['student_no']:$error=array('学号不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $userInfo = TBaseUserProfile::find()->select('email,student_no,school_id')->where('user_id=:userId and del_flag=0',[':userId'=>$userId])->asArray()->one();
            $uemail = $userInfo['email'];
            if ($email != $uemail) {
                $res = TBaseUserProfile::find()->where('email=:email and del_flag=0',[':email'=>$email])->one();
                if($res){
                    $result = [
                        'msg' => '邮箱已存在',
                        'ver' => '1.5.0',
                        'data' => ['邮箱已存在'],
                        'code' => '603'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            if($type=="userType.student" || $type=="userType.teacher"){
                $ustudent_no = $userInfo['student_no'];
                $school = $userInfo['school_id'];
                if ($student_no!=$ustudent_no) {
                    $res = TBaseUserProfile::find()->select('student_no')->where('student_no=:student_no and school_id=:school_id and del_flag=0',[':student_no'=>$student_no,':school_id'=>$school_id])->one();
                    if($res){
                        $result = [
                            'msg' => '学号已存在',
                            'ver' => '1.5.0',
                            'data' => ['学号已存在'],
                            'code' => '603'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
                if ($school_id!=$school) {
                    $res = TBaseUserProfile::find()->select('student_no')->where('student_no=:student_no and school_id=:school_id and del_flag=0',[':student_no'=>$student_no,':school_id'=>$school_id])->one();
                    if($res){
                        $result = [
                            'msg' => '学号已存在',
                            'ver' => '1.5.0',
                            'data' => ['学号已存在'],
                            'code' => '603'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            }
            $transaction = Yii::$app->db->beginTransaction();
            $flag=1;
            try {
                $model = TBaseUserProfile::find()->where('user_id=:userId', [':userId' => $userId])->one();
                $img = $model->url_image;
                $model->attributes = $_REQUEST;
                //处理省市格式（省-市）
                if(!empty($_REQUEST['province'])){
                    $provinceCity=trim($_REQUEST['province'],'-');
                    $provinceCityInfo=explode('-',$provinceCity);
                    $model->province=isset($provinceCityInfo[0])&&!empty($provinceCityInfo[0])?$provinceCityInfo[0]:'请选择省份';
                    $model->city=isset($provinceCityInfo[1])&&!empty($provinceCityInfo[1])?$provinceCityInfo[1]:'请选择城市';
                }
                $model->pet_name = $pet_name;
                $model->gender = $gender;
//                $model->mobilephone = $mobilephone;
                $model->email = $email;
                $model->type = $type;
                $model->school_id = $school_id;
                $model->major_id = $major_id;
                $model->student_no = $student_no;
                if (!empty($studentType)) {
                    $model->student_type = $studentType;
                }
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s",time());
                if(!empty($_REQUEST['url_image'])){
                    $model->url_image = str_replace(Yii::$app->params['fileUrlWeiXin'], "", $_REQUEST['url_image']);
                }else{
                    $model->url_image = $img;
                }
                if($model->validate() && $model->save())
                {
                    $model1 = \app\models\TBaseUser::findOne($userId);
                    if(!empty($project_id)){
                        $model1->project_id = $project_id;
                    }
                    $model1->email = $email;
                    $model1->update_by = $userId;
                    $model1->update_time = date("Y-m-d H:i:s",time());
                    if($model1->save()){
                        $flag=0;
                    }
                    if(!empty($school_id)){
                        $sql="SELECT p.id FROM t_base_project p LEFT JOIN t_base_project_school s ON s.project_id=p.id WHERE s.school_id=:school_id AND p.del_flag=0 AND s.del_flag=0";
                        $params = [':school_id'=>$school_id];
                        $projectId = Yii::$app->db->createCommand($sql)->bindValues($params)->queryScalar();
                        $projectId = !empty($projectId)?$projectId:'-1';
                        $userModel = \app\models\TBaseUser::findOne($userId);
                        if (empty($userModel->project_id)) {
                            $userModel->project_id = $projectId;
                            $userModel->update_time = date('Y-m-d H:i:s',time());
                            $userModel->update_by = $userId;
                            if ($userModel->save()) {
                                $flag=0;
                            } else {
                                $flag=1;
                            }
                        } else {
                            $flag=0;
                        }
                    }
                    else
                    {
                        $flag=0;
                    }
                }
                else
                {
                    $flag=1;
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '修改失败',
                    'ver' => '1.5.0',
                    'data' => ['修改失败'],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
            if($flag==0){
//                $time = date("Y-m-d H:i:s");
//                $userInfoData = [
//                    'userid'=>$model1->old_id,
//                    'birthday'=>'',
//                    'city'=>empty($_REQUEST['city'])?'':$_REQUEST['city'],
//                    'email'=>$email,
//                    'gender'=>$gender,
//                    'institute'=> empty($school_id)?'' : PdUtils::getSchoolName($school_id),
//                    'province'=>empty($_REQUEST['province'])?'':$_REQUEST['province'],
//                    'specialty'=> empty($major_id)?'' :PdUtils::getMajorName($major_id),
//                    'telephone'=>$mobilephone,
//                    'username'=>$model1->username,
//                    'realname'=>$pet_name,
//                    'enrollmentnum'=>empty($student_no)?'':$student_no,
//                    'modifiedtime'=> $time,
//                    'bcourseid'=>'',
//                    'projectid'=>$project_id,
//                ];
//                @PdUtils::SaveMongoData($userInfoData, 'user');
                $transaction->commit();
                //返回修改后的个人信息
                $this->AppUserInfo($userId,'');
                $result = [
                    'msg' => '修改成功',
                    'ver' => '1.5.0',
                    'data' => ['修改成功'],
                    'success' => true,
                    'code' => '200'
                ];
            }else{
                $transaction->rollBack();
                $result = [
                    'msg' => '修改失败',
                    'ver' => '1.5.0',
                    'data' => ['修改失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序学校列表接口
     * @param int  userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppGetSchoolPageList()
    {
        $error = array();
        $school_name = !empty($_REQUEST['school_name'])?$_REQUEST['school_name']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $where="";
            if(!empty($school_name)){
                $where.=" and school_name like '%".$school_name."%'";
            }
//            $school_list = TBaseSchool::find()->select('id,school_name,pinyin,school_code')->where(['del_flag' => 0])->asArray()->all();
            $sql="select id,school_name,pinyin,school_code from t_base_school where del_flag=0 ".$where;
            $school_list=\yii::$app->db->createCommand($sql)->queryAll();
            if($school_list)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($school_list),
                    'success' => true,
                    'code' => 200,
                ];
            }
            elseif(empty($school_list))
            {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => ['没有查询到相关数据'],
                    'success' => false,
                    'code' => 404,
                ];
            }
            elseif($school_list===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['查找失败'],
                    'success' => false,
                    'code' => 400,
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序专业列表接口
     * @param int  school_id:学校ID department_id:院系ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppGetMajorPageList()
    {
        $error = array();
//        $school_id = !empty($_REQUEST['school_id'])?$_REQUEST['school_id']:'';
//        $department_id = !empty($_REQUEST['department_id'])?$_REQUEST['department_id']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $major_name=isset($_REQUEST['major_name'])?$_REQUEST['major_name']:'';
        $where = '';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
//            if(!empty($school_id))
//            {
//                $where .= " and school_id='".$school_id."'";
//            }
//            if(!empty($department_id))
//            {
//                $where .= " and department_id='".$department_id."'";
//            }
            if(!empty($major_name))
            {
                $where .= " and name like '%".$major_name."%'";
            }
            $major_sql = "SELECT uuid,name FROM t_base_major_directory WHERE del_flag=0 ".$where." ORDER BY id";
            $major = Yii::$app->db->createCommand($major_sql)->queryAll();
            if($major)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($major),
                    'success' => true,
                    'code' => 200,
                ];
            }
            elseif(empty($major))
            {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => ['没有查询到相关数据'],
                    'success' => false,
                    'code' => 404,
                ];
            }
            elseif($major===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['查找失败'],
                    'success' => false,
                    'code' => 400,
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序联盟列表
     * @param int  taskId:任务ID  projectId:联盟ID userId:用户ID reportId:报告ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppProjectList(){
        $unionName=isset($_REQUEST['unionName'])&&!empty($_REQUEST['unionName']) ? $_REQUEST['unionName'] : '' ;
        $error = array();
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>[],
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }else{
            $where="";
            if(!empty($unionName)){
                $where .= " AND name like '%".$unionName."%'";
            }
            $sql = "SELECT id,name FROM t_base_project WHERE del_flag=0 ".$where;
            $data = Yii::$app->db->createCommand($sql)->queryAll();
            if($data){
                $result = array(
                    "msg"=> "查询成功",
                    "ver"=> "1.5.0",
                    'data'=>$data,
                    'code'=>'200'
                );
            }else{
                $result = array(
                    "msg"=> "查询失败",
                    "ver"=> "1.5.0",
                    'data'=>['查询失败'],
                    'code'=>'404'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序注册接口
     * @param string  username:用户名 password:密码 code:验证码
     * @return mixed 错误返回空，正确返回json
     * @date: 2018-12-26
     * @author: gyq
     */
    public function actionRegister() {
        $error = array();
        $username = isset($_REQUEST['username']) && !empty($_REQUEST['username']) ? $_REQUEST['username'] : $error = array('用户名不能为空');
        $password = isset($_REQUEST['password']) && !empty($_REQUEST['password']) ? $_REQUEST['password'] : $error = array('密码不能为空');
        $userType = isset($_REQUEST['userType']) && !empty($_REQUEST['userType']) ? $_REQUEST['userType'] : $error = array('角色类型不能为空');
//        $code     = isset($_REQUEST['code']) ? $_REQUEST['code'] : $error = array('验证码不能为空');
        $openid     = isset($_REQUEST['openid']) ? $_REQUEST['openid'] : '';
        $project_id = isset($_REQUEST['project_id']) ? $_REQUEST['project_id'] : '';
        $studentType = !empty($_REQUEST['studentType']) ? $_REQUEST['studentType'] : '';
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        }
//        $status = $this->CheckSms($username, $code, 'sendMsgBusinessType.register');
        $status=1;
        if ($status) {
            $transaction = Yii::$app->db->beginTransaction();
            $sql = "select * from t_base_user_profile where mobilephone=:username and del_flag=0";
            $info = \Yii::$app->db->createCommand($sql)->bindValues([':username'=>$username])->queryOne();
            if (!empty($info)) {
                $result = array(
                    "msg" => "用户名已存在",
                    "ver" => "1.5.0",
                    'data' => ['用户名已存在'],
                    'success' => false,
                    'code' => '400'
                );
                Yii::$app->end(json_encode($result));
            } else {
                $model = new TBaseUser();
                $model->id = Uuid::uuid();
                $model->salt = self::getRandomString(6);
                $model->username = $username;
                $model->password = md5($password . $model->salt);
                $model->regdate = date("Y-m-d H:i:s", time());
                $model->create_time = date('Y-m-d H:i:s', time());
                $model->hashkey = 0;
                $model->old_id = $model->id;
                $model->project_id = $project_id;
                $model->del_flag = 0;
                if ($model->validate() && $model->save()) {
                    $profile = new TBaseUserProfile();
                    $profile->id = Uuid::uuid();
                    $profile->user_id = $model->id;
                    $profile->type = $userType;
                    $profile->gender = 'gender.male';
                    $profile->mobilephone = $username;
                    $profile->student_type = $studentType;
                    $profile->create_by = $model->id;
                    $profile->create_time = date('Y-m-d H:i:s');
                    $profile->del_flag = 0;
                    if ($profile->validate() && $profile->save()) {
                        $transaction->commit();
                        //注册用户
//                        $time = date("Y-m-d H:i:s");
//                        $userInfo = [
//                            'userid' => $model->id,
//                            'birthday' => '',
//                            'city' => '',
//                            'email' => '',
//                            'gender' => '',
//                            'institute' => '',
//                            'province' => '',
//                            'role' => PdUtils::getPersonnel($userType),
//                            'specialty'=>'',
//                            'telephone' => $username,
//                            'username' => $username,
//                            'realname' => '',
//                            'enrollmentnum' => '',
//                            'createdtime' => $time,
//                            'modifiedtime' => $time,
//                            'bcourseid' => '',//组课id
//                            'projectid' => $project_id,
//                        ];
//                        @PdUtils::SaveMongoData($userInfo, 'user');
                        //用户行为日志表
//                        $logInfo = [
//                            'time' => $time,
//                            'operation_code' => '11000013',
//                            'operation_name' => '注册用户',
//                            'courseid' => '',
//                            'equipment' => PdUtils::EQUIPMENT_PC,
//                            'ip' => \Yii::$app->request->userIP,
//                            'objectid' => $model->id,
//                            'bcourseid' => '',
//                            'projectid' => $project_id,
//                            'userid' => $model->id,
//                        ];
//                        @PdUtils::SaveMongoData($logInfo, 'log-info');
                        //注册成功返回用户信息
                        $this->AppUserInfo($model->old_id,$openid);
                    } else {
                        $transaction->rollback();
                        $result = array(
                            "msg" => "注册失败",
                            "ver" => "1.5.0",
                            'data' => ['注册失败'],
                            'code' => '400'
                        );
                    }
                    Yii::$app->end(json_encode($result));
                } else {
                    $transaction->rollback();
                    $result = array(
                        "msg" => "注册失败",
                        "ver" => "1.5.0",
                        'data' => ['注册失败'],
                        'code' => '400'
                    );
                    Yii::$app->end(json_encode($result));
                }
            }
        } else {
            $result = array(
                "msg" => "验证码错误",
                "ver" => "1.5.0",
                'data' => ['验证码错误'],
                'success' => false,
                'code' => '400'
            );
        }
        Yii::$app->end(json_encode($result));
    }
    /**
     * 微信小程序密码找回：验证code之后返回用户uid
     * gyq
     * 2019/12/26
     */
    public function actionReturnUserInfo() {
        $error = array();
        $phone = isset($_REQUEST['phone']) ? $_REQUEST['phone'] : $error = array('手机号不能为空');
        $code = isset($_REQUEST['code']) ? $_REQUEST['code'] : $error = array('手机验证码不能为空');
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : $error = array('业务类型不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $val = $this->CheckSms($phone, $code, $type);
            if ($val) {
                $profile = TBaseUserProfile::find()->where('mobilephone=:phone and del_flag=0', [':phone' => $phone])->asArray()->one();
                $result = array(
                    "msg" => "验证码正确",
                    "ver" => "1.5.0",
                    'data' => array('user_id' => $profile['user_id']),
                    'code' => '200'
                );
            } else {
                $result = array(
                    "msg" => "验证码错误",
                    "ver" => "1.5.0",
                    'data' => ['验证码错误'],
                    'code' => '600'
                );
            }
            \yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序修改密码
     * gyq
     * 2019/12/26
     */
    public function actionRecoverPassword() {
        $error = array();
        $user_id = !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error = array('用户id不能为空');
        $oldPassword = !empty($_REQUEST['oldPassword']) ? $_REQUEST['oldPassword'] : '';
        $password = !empty($_REQUEST['password']) ? $_REQUEST['password'] : $error = array('密码不能为空');
        $repassword = !empty($_REQUEST['repassword']) ? $_REQUEST['repassword'] : $error = array('确认密码不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $salt = TBaseUser::findOne($user_id);
            if (!empty($oldPassword)) {
                if ($salt->password != md5($oldPassword . $salt->salt)) {
                    $result = array(
                        "msg" => "原始密码错误",
                        "ver" => "1.5.0",
                        'data' => ['原始密码错误'],
                        'code' => '400'
                    );
                    Yii::$app->end(json_encode($result));
                }
            }
            if ($password === $repassword) {
                $res = TBaseUser::updateAll(['password' => md5($password . $salt->salt), 'update_by' => $user_id, 'update_time' => date('Y-m-d H:i:s')], ['id' => $user_id]);
                if ($res != false) {
                    $result = array(
                        "msg" => "修改成功",
                        "ver" => "1.5.0",
                        'data' => ['修改成功'],
                        'code' => '200'
                    );
                } else {
                    $result = array(
                        "msg" => "修改失败",
                        "ver" => "1.5.0",
                        'data' => ['修改失败'],
                        'code' => '400'
                    );
                }
                Yii::$app->end(json_encode($result));
            } else {
                $result = array(
                    "msg" => "密码不一致",
                    "ver" => "1.5.0",
                    'data' => ['密码不一致'],
                    'code' => '400'
                );
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /**
     * 微信小程序发送验证码
     * phone 发送手机号
     * type  短信类型
     */
    public function actionSendSms() {
        $phone = isset($_REQUEST['phone']) && !empty($_REQUEST['phone']) ? $_REQUEST['phone'] : $error[] = array('手机号不能为空');
        $type  = isset($_REQUEST['type']) && !empty($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('操作类型不能为空');
        $userType  = isset($_REQUEST['userType']) && !empty($_REQUEST['userType']) ? $_REQUEST['userType'] : "";//登录端类型
        if(!empty($error)){
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(urldecode(json_encode($result)));
        }
        //登录操作校验角色账号与登录端是否统一
        if(!empty($userType)){
            $sql="SELECT
	p.type
FROM
	t_base_user_profile p
LEFT JOIN t_base_user u ON p.user_id = u.id
WHERE
	u.del_flag = 0
AND p.del_flag = 0
AND (
	u.username =:phone
	OR p.mobilephone =:phone
)";
            $roleType=\yii::$app->db->createCommand($sql)->bindValues([':phone'=>$phone])->queryScalar();
            if($userType=='userType.student'){
            //学生端短信登录
                if(!in_array($roleType,['userType.student','userType.society','userType.company'])) {
                    $result = [
                        "msg" => "您目前账号是教师身份，请前往“微知库教师版”小程序登录",
                        "ver" => "1.5.0",
                        'type' => '4.0',
                        'data' => ['您目前账号是教师身份，请前往“微知库教师版”小程序登录'],
                        'code' => '400'
                    ];
                    \yii::$app->end(json_encode($result));
                }
            }else if($userType=='userType.teacher'){
                //教师端短信登录
                if($roleType!='userType.teacher'){
                    $role="学生";
                    if($roleType=='userType.student'){
                        $role="学生";
                    }else if($roleType=='userType.society'){
                        $role="社会学习者";
                    }else if($roleType=='userType.company'){
                        $role="企业";
                    }
                    $msg="您目前账号是".$role."身份，请前往“微知库学生版”小程序登录";
                    $result = [
                        "msg" => $msg,
                        "ver" => "1.5.0",
                        'type'=>'4.0',
                        'data' =>[$msg],
                        'code' => '400'
                    ];
                    \yii::$app->end(json_encode($result));
                }
            }
        }
//        $phone = $_REQUEST['phone'];
//        $type = $_REQUEST['type'];
        if($type=='sendMsgBusinessType.changePhonenumber'){
            //个人信息修改手机号码
            $code = rand(1000, 9999);
            $content = "您的验证码是：{$code}，祝您学习愉快。如非本人操作，请忽略本信息【微知库】";
            $result_code = self::SendOnce($phone, $content, $type, '', $code);
        }else{
            $res = TBaseUserProfile::find()->where('mobilephone=:mobilephone and del_flag=0', [':mobilephone' => $phone])->one();
            if (!empty($res)) {
                if ($type == "sendMsgBusinessType.register") {
                    $result = array(
                        "msg" => "该手机号已注册",
                        "ver" => "1.5.0",
                        'data' => ['该手机号已注册'],
                        'code' => '400'
                    );
                    \Yii::$app->end(json_encode($result));
                }
            } else {
                if ($type == "sendMsgBusinessType.singin" || $type == "sendMsgBusinessType.recoverPassword") {
                    $result = array(
                        "msg" => "请填写正确的手机号码！",
                        "ver" => "1.5.0",
                        'data' => ['请填写正确的手机号码'],
                        'code' => '404'
                    );
                    \Yii::$app->end(json_encode($result));
                }
            }
            $code = rand(1000, 9999);
            $content = "您的验证码是：{$code}，祝您学习愉快。如非本人操作，请忽略本信息【微知库】";
            $result_code = self::SendOnce($phone, $content, $type, '', $code);
        }
        if ($result_code['resultCode'] == 1) {
            $result = array(
                "msg" => "发送成功",
                "ver" => "1.5.0",
                'data' => ['发送成功'],
                'code' => '200'
            );
        }elseif ($result_code['resultCode'] == 13) {
            $result = array(
                "msg" => "手机号段不支持",
                "ver" => "1.5.0",
                'data' => ['手机号段不支持'],
                'code' => $result_code['resultCode']
            );
        } else {
            $result = array(
                "msg" => "发送失败",
                "ver" => "1.5.0",
                'data' => ['发送失败'],
                'code' => $result_code['resultCode']
            );
        }
        \Yii::$app->end(json_encode($result));
    }
    /**
     * 微信小程序根据openid获取用户信息
     * @param type $openid
     */
    public function actionGetUserInfoByOpenId(){
        $openId=isset($_REQUEST['openid'])&&!empty($_REQUEST['openid']) ? $_REQUEST['openid'] : "" ;
        if(empty($openId)){
            $result = array(
                "msg" => "openid不能为空",
                "ver" => "1.5.0",
                'data' => ['openid不能为空'],
                'code' => 601
            );
            \Yii::$app->end(json_encode($result));
        }else{
            $sql="select * from t_base_user where del_flag=0 and open_id=:openId";
            $userInfo=\yii::$app->db->createCommand($sql)->bindValues([':openId'=>$openId])->queryOne();
            if(empty($userInfo)){
                //微信未绑定微知库账号
                $result = array(
                    "msg" => "微信未绑定账号,需要进行绑定操作",
                    "ver" => "1.5.0",
                    'data' => '微信未绑定账号,需要进行绑定操作',
                    'code' => 200
                );
                \Yii::$app->end(json_encode($result));
            }else{
                //微信绑定过微知库账号返回该用户对应的信息
                $this->AppUserInfo($userInfo['id'],'');
            }
        }
    }
    /**
     * 微信小程序验证短信功能。
     * @param type $phone
     * @param type $code
     * @param type $type
     * @return boolean
     */
    public static function CheckSms($phone, $code, $type) {
        $sms = TBaseSmsLog::find()->where('mobile=:phone and type=:t  and create_time>=:beginTime', array(
            ':phone' => $phone,
            ':t' => $type,
            ':beginTime' => date('Y-m-d H:i:s', time() - 600)
        ))->orderBy(['create_time' => SORT_DESC])->limit(1)->asArray()->one();
        if (empty($sms)) {
            return FALSE;
        } else if ($sms['msg_id'] != $code) {
            return FALSE;
        } else {
            return TRUE;
        }
    }
    /**
     * 微信小程序随机数获取
     * @param type $len
     * @param string $chars
     * @return string
     */
    public static function getRandomString($len, $chars = null) {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double) microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
    /**
     * 微信小程序短信接口
     * User:gyq
     * date:2019/12/26
     */
    public static function SendOnce($phone, $content, $type, $device_id, $code) {
        $return = array('resultCode' => 1, 'message' => '');
        //echo json_encode($return);Yii::app()->end();
        //是否允许发送短信验证码（10次/天）
        $day_begin_time = strtotime(date('Y-m-d'));
        $day_end_time = time();
        $daySendNum = TBaseSmsLog::find()->where('mobile=:phone and type=:t  and (create_time>=:beginTime and create_time<=:endTime)', array(
            ':phone' => $phone,
            ':t' => $type,
            ':beginTime' => $day_begin_time,
            ':endTime' => $day_end_time
        ))->count();
        if ($daySendNum >= self::SMS_LIMIT_DAY) {
            $return['resultCode'] = 3;
            $return['message'] = '今天短信验证码发送已达到上限.';
            return $return;
        }
        //是否允许发送短信验证码（3次/时）
        $hour_begin_time = strtotime(date('Y-m-d H:00:00'));
        $hour_end_time = time();
        $hourSendNum = TBaseSmsLog::find()->where('mobile=:phone and type=:t  and (create_time>=:beginTime and create_time<=:endTime)', array(
            ':phone' => $phone,
            ':t' => $type,
            ':beginTime' => $hour_begin_time,
            ':endTime' => $hour_end_time
        ))->count();
        if ($hourSendNum >= self::SMS_LIMIT_HOUR) {
            $return['resultCode'] = 4;
            $return['message'] = '短信验证码发送太过频繁，请稍后再发.';
            return $return;
        }
        //写入表
        $transaction = Yii::$app->db->beginTransaction();
        $smsCode = new TBaseSmsLog();
        $smsCode->id = Uuid::uuid();
        $smsCode->mobile = $phone;
        $smsCode->device_id = $device_id;
        $smsCode->content = $content;
        $smsCode->type = $type;
        $smsCode->msg_id = $code;
        $smsCode->create_time = date('Y-m-d H:i:s');
        if ($smsCode->validate() && $smsCode->save()) {
            $username = 'linghanghy'; //用户名
            $password = '7CCpfT'; //原密码
            $data = array(
                'username' => $username, //用户名
                'password' => $password, //原密码
                'content' => $content, //短信内容
                'mobile' => $phone, //手机号码
                'productid' => '676767', //产品id
                'xh' => ''//小号
            );
            $res = self::sendSMS('POST', $data); //GET or POST
            $result = explode(",", $res);

            if (trim($result[0]) != 1) {
                $transaction->rollback();
                $return['resultCode'] = trim($result[0]);
                $return['message'] = '发送失败';
            } else {
                $transaction->commit();
                $return['resultCode'] = trim($result[0]);
                $return['message'] = '发送成功';
            }
            return $return;
        } else {
            return $smsCode->errors;
        }
    }
    public static function sendSMS($type, $data, $isTranscoding = false) {
        $data['content'] = $isTranscoding === true ? mb_convert_encoding($data['content'], "UTF-8") : $data['content'];
        $data['username'] = $data["username"];
        $data['tkey'] = date('YmdHis');
        $data['password'] = md5(md5($data["password"]) . $data['tkey']);

        return $type == "POST" ? self::httpPost($data) : self::httpGet($data);
    }
    public static function hGet($url, $data) {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, self::timeout); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Error POST' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $result; // 返回数据
    }
    public static function httpPost($data) { // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, self::APIUrl); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)"); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, self::timeout); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Error POST' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $result; // 返回数据
    }
    /**
     * 微信小程序根据用户id获取用户详细信息
     */
    public static function AppUserInfo($uid,$openid) {
        $sql = "select id,pet_name,mobilephone,type,school_id,major_id,url_image,email,gender,year,birthday,province,city,address,student_no,qianming from t_base_user_profile where user_id='" . $uid . "' and del_flag=0";
        $info = \Yii::$app->db->createCommand($sql)->queryOne();
        //为微信小程序处理省市数据
        $city=empty($info['city']) || $info['city']=='null' ? '请选择城市' : $info['city'];
        $province=empty($info['province'])||$info['province']=='null' ? '请选择省份' : $info['province'];
        $info['province']=$province."-".$city;
        //处理详细地址
        $address=empty($info['address'])||$info['address']=='null' ? '' : $info['address'];
        $info['address']=$address;
        //处理出生日期格式
        if(!empty($info['birthday'])){
            $info['birthday']=substr($info['birthday'],0,10);
        }
        if (isset($info['school_id'])) {
            $sql="select school_name from t_base_school where del_flag=0 and id=:id";
            $school_name =\yii::$app->db->createCommand($sql)->bindValues([':id'=>$info['school_id']])->queryScalar();
            $info['school_name'] = !empty($school_name) ? $school_name : '';
        } else {
            $info['school_name'] = '';
            $info['school_id'] = '';
        }
        if (isset($info['major_id'])) {
            $sql="select name from t_base_major_directory where del_flag=0 and uuid=:uuid";
            $major_name=\yii::$app->db->createCommand($sql)->bindValues([':uuid'=>$info['major_id']])->queryScalar();
            $info['major_name'] = !empty($major_name) ? $major_name : "";
        } else {
            $info['major_name'] = '';
            $info['major_id'] = '';
        }
        $class_id = TBaseClassMember::find()->select('class_id')->where('user_id=:userId and status=:status and del_flag=0', [':userId' => $uid, ':status' => 'classMember.regulars'])->asArray()->one();
        if ($class_id) {
            $info['class_id'] = $class_id['class_id'];
        } else {
            $info['class_id'] = '';
        }
        $role_sql = "SELECT tbr.role_desc FROM t_base_role tbr LEFT JOIN t_base_user_role tbur ON tbur.role_id=tbr.id WHERE tbur.user_id='" . $uid . "' and tbr.del_flag=0 and tbur.del_flag=0";
        $role_name = \Yii::$app->db->createCommand($role_sql)->queryOne();
        $info['role_name'] = isset($role_name['role_desc']) ? $role_name['role_desc'] : '';

        $info['email'] = isset($info['email']) ? $info['email'] : '';
        $info['url_image'] = !empty($info['url_image']) ? Yii::$app->params['fileUrlWeiXin'] . $info['url_image'] : '';
        $info['gender'] = isset($info['gender']) ? $info['gender'] : '';
        $info['year'] = isset($info['year']) ? $info['year'] : '';
        $info['student_no'] = isset($info['student_no']) ? $info['student_no'] : '';
        $info['pet_name'] = isset($info['pet_name']) ? $info['pet_name'] : '';
        $info['type'] = isset($info['type']) ? $info['type'] : '';
        $info['qianming'] = isset($info['qianming']) ? $info['qianming'] : '';
        //返回联盟id，后期需要修改
        // $info['project_id'] = isset($info['project_id']) ? $info['project_id'] : '';
        $user = TBaseUser::findOne($uid);
        if (!empty($user->project_id)) {
            if($user->project_id=="-1"){
                $info['project_name'] = '';
            }else{
                $project_name = \app\models\TBaseProject::findOne($user->project_id);
                $info['project_name'] = !empty($project_name)?$project_name->name:'';
            }
        } else {
            $info['project_name'] = '';
        }
        if (!empty($info['url_image'])) {
            $info['url_image'] = $info['url_image'];
        }
        $data = array('uid' => $user->id, 'username' => $user->username,'project_id'=>$user->project_id,'old_id'=>$user->old_id);
        if(!empty($openid)){
            //绑定openid
            $sql="UPDATE t_base_user
SET open_id =:open_id,
 update_time =:update_time,
 update_by=:id
WHERE
	del_flag = 0
AND id =:id";
            \yii::$app->db->createCommand($sql)->bindValues([
                ':open_id'=>$openid,
                'update_time'=>date('Y-m-d H:i:s',time()),
                ':id'=>$uid
            ])->execute();
        }
        //openid
        $sql="select open_id from t_base_user where del_flag=0 and id=:userId";
        $info['openid']=\yii::$app->db->createCommand($sql)->bindValues([':userId'=>$uid])->queryScalar();
        $result = array(
            "msg" => "操作成功",
            "ver" => "1.5.0",
            'data' => array_merge($data, $info),
            'code' => '200'
        );
        Yii::$app->end(json_encode($result));
    }
    /**
     * 微信小程序用户解绑
     */
    public function actionUnbind(){
        $uid=!empty($_REQUEST['userId'])?$_REQUEST['userId']:$errors[]="用户ID不能为空";
        $openid=!empty($_REQUEST['openid'])?$_REQUEST['openid']:$errors[]="openid不能为空";
        if(!empty($errors)){
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $errors,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        }else{
            $sql="update t_base_user set open_id='',update_time=:update_time,update_by=:update_by where id=:update_by and open_id=:openId";
            $res=\yii::$app->db->createCommand($sql)->bindValues([
                ':update_time'=>date('Y-m-d H:i:s',time()),
                ':update_by'=>$uid,
                ':openId'=>$openid
            ])->execute();
            if($res){
                $result = array(
                    "msg" => "解绑成功",
                    "ver" => "1.5.0",
                    'data' => ['解绑成功'],
                    'code' => '200'
                );
            }else{
                $result = array(
                    "msg" => "解绑失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序根据用户id获取用户详细信息
     */
    public function actionGetUserInfoById() {
        $uid=!empty($_REQUEST['userId'])?$_REQUEST['userId']:$errors[]="用户ID不能为空";
        if(!empty($errors)){
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => $errors,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        }
        $sql = "select id,pet_name,mobilephone,type,school_id,major_id,url_image,email,gender,year,student_no,qianming from t_base_user_profile where user_id='" . $uid . "' and del_flag=0";
        $info = \Yii::$app->db->createCommand($sql)->queryOne();
        if (isset($info['school_id'])) {
            $school_name = TBaseSchool::find()->select('school_name')->where('id=:id and del_flag=0', [':id' => $info['school_id']])->asArray()->one();
            $info['school_name'] = isset($school_name['school_name']) ? $school_name['school_name'] : '';
        } else {
            $info['school_name'] = '';
            $info['school_id'] = '';
        }
        if (isset($info['major_id'])) {
            $major_name = TBaseMajor::find()->select('name')->where('id=:id and del_flag=0', [':id' => $info['major_id']])->asArray()->one();
            $info['major_name'] = $major_name['name'] ? $major_name['name'] : "";
        } else {
            $info['major_name'] = '';
            $info['major_id'] = '';
        }
        $class_id = TBaseClassMember::find()->select('class_id')->where('user_id=:userId and status=:status and del_flag=0', [':userId' => $uid, ':status' => 'classMember.regulars'])->asArray()->one();
        if ($class_id) {
            $info['class_id'] = $class_id['class_id'];
        } else {
            $info['class_id'] = '';
        }

        $role_sql = "SELECT tbr.role_desc FROM t_base_role tbr LEFT JOIN t_base_user_role tbur ON tbur.role_id=tbr.id WHERE tbur.user_id='" . $uid . "' and tbr.del_flag=0 and tbur.del_flag=0";
        $role_name = \Yii::$app->db->createCommand($role_sql)->queryOne();
        $info['role_name'] = isset($role_name['role_desc']) ? $role_name['role_desc'] : '';

        $info['email'] = isset($info['email']) ? $info['email'] : '';
        $info['url_image'] = !empty($info['url_image']) ? Yii::$app->params['fileUrlWeiXin'] . $info['url_image'] : '';
        $info['gender'] = isset($info['gender']) ? $info['gender'] : '';
        $info['year'] = isset($info['year']) ? $info['year'] : '';
        $info['student_no'] = isset($info['student_no']) ? $info['student_no'] : '';
        $info['pet_name'] = isset($info['pet_name']) ? $info['pet_name'] : '';
        $info['type'] = isset($info['type']) ? $info['type'] : '';
        $info['qianming'] = isset($info['qianming']) ? $info['qianming'] : '';

        //返回联盟id，后期需要修改
        // $info['project_id'] = isset($info['project_id']) ? $info['project_id'] : '';
        $user = TBaseUser::findOne($uid);
        if (!empty($user->project_id)) {
            if($user->project_id=="-1"){
                $info['project_name'] = '';
            }else{
                $project_name = \app\models\TBaseProject::findOne($user->project_id);
                $info['project_name'] = !empty($project_name)?$project_name->name:'';
            }
        } else {
            $info['project_name'] = '';
        }
        if (!empty($info['url_image'])) {
            $info['url_image'] = Yii::$app->params['fileUrlWeiXin'] . $info['url_image'];
        }
        $data = array('uid' => $user->id, 'username' => $user->username,'project_id'=>$user->project_id,'old_id'=>$user->old_id);
        $result = array(
            "msg" => "查询成功",
            "ver" => "1.5.0",
            'data' => array_merge($data, $info),
            'code' => '200'
        );
        Yii::$app->end(json_encode($result));
    }
    /**
     * 微信小程序重置用户名接口
     * @param string  username:用户名 mobilephone:手机号
     * @return mixed 错误返回空，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionResetUsername() {
        $error = array();
        $username = !empty($_POST['username']) ? $_POST['username'] : $error = array('用户名不能为空');
        $userId = !empty($_POST['userId']) ? $_POST['userId'] : $error = array('用户ID不能为空');
//        $password = !empty($_POST['password']) ? $_POST['password'] : $error = array('密码不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $user = TBaseUser::find()->where(['username' => $username, 'del_flag' => 0])->one();
            if ($user) {
                $result = array(
                    "msg" => "用户名已存在",
                    "ver" => "1.5.0",
                    'data' => ['用户名已存在'],
                    'success' => false,
                    'code' => '400'
                );
                Yii::$app->end(json_encode($result));
            }
            $model = TBaseUser::findOne($userId);
            if ($model) {
//                if ($model['password'] != md5($password . $model['salt'])) {
//                    $result = array(
//                        "msg" => "输入密码错误",
//                        "ver" => "1.5.0",
//                        'data' => ['输入密码错误'],
//                        'code' => '400'
//                    );
//                    Yii::$app->end(json_encode($result));
//                }
                $model->username = $username;
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s", time());
                if ($model->validate() && $model->save()) {
                    $result = array(
                        "msg" => "修改成功",
                        "ver" => "1.5.0",
                        'data' => ['修改成功'],
                        'success' => true,
                        'code' => '200'
                    );
                } else {
                    $result = array(
                        "msg" => "修改失败",
                        "ver" => "1.5.0",
                        'data' => ['修改失败'],
                        'success' => false,
                        'code' => '400'
                    );
                }
                Yii::$app->end(json_encode($result));
            } else {
                $result = array(
                    "msg" => "没有该用户",
                    "ver" => "1.5.0",
                    'data' => ['用户不存在'],
                    'success' => false,
                    'code' => '404'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /*微信小程序获取全部省份*/
    public function actionGetAllProvince(){
        $data=[
            '1'=>'北京市',
            '2'=>'天津市',
            '3'=>'河北省',
            '4'=>'山西省',
            '5'=>'内蒙古自治区',
            '6'=>'辽宁省',
            '7'=>'吉林省',
            '8'=>'黑龙江省',
            '9'=>'上海市',
            '10'=>'江苏省',
            '11'=>'浙江省',
            '12'=>'安徽省',
            '13'=>'福建省',
            '14'=>'江西省',
            '15'=>'山东省',
            '16'=>'河南省',
            '17'=>'湖北省',
            '18'=>'湖南省',
            '19'=>'广东省',
            '20'=>'广西壮族自治区',
            '21'=>'海南省',
            '22'=>'重庆市',
            '23'=>'四川省',
            '24'=>'贵州省',
            '25'=>'云南省',
            '26'=>'西藏自治区',
            '27'=>'陕西省',
            '28'=>'甘肃省',
            '29'=>'青海省',
            '30'=>'宁夏回族自治区',
            '31'=>'新疆维吾尔族自治区',
            '32'=>'台湾',
            '33'=>'香港特别行政区',
            '34'=>'澳门特别行政区',
        ];
        foreach($data as $key=>$value){
            $info[]=['provinceId'=>$key,'provinceName'=>$value];
        }
        $result = array(
            "msg" => "查询成功",
            "ver" => "1.5.0",
            'data' => $info,
            'success' => true,
            'code' => '200'
        );
        \yii::$app->end(json_encode($result));
    }
    /*
     * 微信小程序省市二级联动
     * */
    public function actionGetCityByProvince(){
        $provinceId = !empty($_REQUEST['provinceId']) ? (int)$_REQUEST['provinceId'] : $error[]= array('省Id不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $data=[
                '1'=>['北京市'],
                '2'=>['天津市'],
                '3'=>['石家庄市','唐山市','秦皇岛','邯郸市','邢台市','保定市','张家口','承德市','沧州市','廊坊市','衡水市'],
                '4'=>['太原市','大同市','阳泉市','长治市','晋城市','朔州市','晋中市','运城市','忻州市','临汾市','吕梁市'],
                '5'=>['呼和浩特','包头市','乌海市','赤峰市','通辽市','呼伦贝尔','兴安盟'],
                '6'=>['沈阳市','大连市','鞍山市','抚顺市','本溪市','丹东市','锦州市','营口市','阜新市','辽阳市','盘锦市','铁岭市','朝阳市','葫芦岛市'],
                '7'=>['长春市','吉林市','四平市','辽源市','通化市','白山市','松原市','白城市','延边朝鲜族'],
                '8'=>['哈尔滨市','齐齐哈尔市','鸡西市','鹤岗市','双鸭山市','大庆市','伊春市','佳木斯市','七台河市','牡丹江市','黑河市','绥化市','大兴安岭'],
                '9'=>['上海市'],
                '10'=>['南京市','无锡市','徐州市','常州市','苏州市','南通市','连云港市','淮安市','盐城市','扬州市','镇江市','泰州市','宿迁市'],
                '11'=>['杭州市','宁波市','温州市','嘉兴市','湖州市','绍兴市','金华市','衢州市','舟山市','台州市','丽水市'],
                '12'=>['合肥市','芜湖市','蚌埠市','淮南市','马鞍山市','淮北市','铜陵市','安庆市','黄山市','滁州市','阜阳市','宿州市','巢湖市','六安市','亳州市','池州市','宣城市'],
                '13'=>['福州市','厦门市','莆田市','三明市','泉州市','漳州市','南平市','龙岩市','宁德市'],
                '14'=>['南昌市','景德镇市','萍乡市','九江市','新余市','鹰潭市','赣州市','吉安市','宜春市','抚州市','上饶市'],
                '15'=>['济南市','青岛市','淄博市','枣庄市','东营市','烟台市','潍坊市','济宁市','泰安市','威海市','日照市','莱芜市','临沂市','德州市','聊城市','滨州市','荷泽市'],
                '16'=>['郑州市','开封市','洛阳市','平顶山市','安阳市','鹤壁市','新乡市','焦作市','濮阳市','许昌市','漯河市','三门峡市','南阳市','商丘市','信阳市','周口市','驻马店市'],
                '17'=>['武汉市','黄石市','十堰市','宜昌市','襄樊市','鄂州市','荆门市','孝感市','荆州市','黄冈市','咸宁市','随州市','恩施土家族苗族'],
                '18'=>['长沙市','株洲市','湘潭市','衡阳市','邵阳市','岳阳市','常德市','张家界市','益阳市','郴州市','永州市','怀化市','娄底市','湘西土家族苗族'],
                '19'=>['广州市','韶关市','深圳市','珠海市','汕头市','佛山市','江门市','湛江市','茂名市','肇庆市','惠州市','梅州市','汕尾市','河源市','阳江市','清远市','东莞市','中山市','潮州市','揭阳市','云浮市'],
                '20'=>['南宁市','柳州市','桂林市','梧州市','北海市','防城港市','钦州市','贵港市','玉林市','百色市','贺州市','河池市','来宾市','崇左市'],
                '21'=>['海口市','三亚市'],
                '22'=>['重庆市'],
                '23'=>['成都市','自贡市','攀枝花市','泸州市','德阳市','绵阳市','广元市','遂宁市','内江市','乐山市','南充市','眉山市','宜宾市','广安市','达州市','雅安市','巴中市','资阳市','阿坝藏族','甘孜藏族','凉山彝族'],
                '24'=>['贵阳市','六盘水市','遵义市','安顺市','铜仁市','黔西南布依族苗族','毕节市','黔东南苗族侗族','黔南布依族苗族'],
                '25'=>['昆明市','曲靖市','玉溪市','保山市','昭通市','丽江市','临沧市','楚雄彝族','红河哈尼族彝族'],
                '26'=>['拉萨市','昌都','山南','日喀则','那曲地区','阿里地区','林芝地区'],
                '27'=>['西安市','铜川市','宝鸡市','咸阳市','渭南市','延安市','汉中市','榆林市','安康市','商洛市'],
                '28'=>['兰州市','嘉峪关市','金昌市','白银市','天水市','武威市','张掖市','平凉市','酒泉市','庆阳市','定西市','陇南市'],
                '29'=>['西宁市','海东','海北','黄南','海南','果洛','玉树','海西'],
                '30'=>['银川市','石嘴山市','吴忠市','固原市','中卫市'],
                '31'=>['乌鲁木齐市','克拉玛依市','吐鲁番地区','哈密地区','昌吉回族','博尔塔拉','巴音郭楞','阿克苏地区'],
                '32'=>['新北市','台北市','台中市','高雄市','基隆市'],
                '33'=>['香港特别行政区'],
                '34'=>['澳门特别行政区'],
            ];
            $data=isset($data[$provinceId])&&!empty($data[$provinceId]) ? $data[$provinceId] : [];
            foreach ($data as $key=>$value){
                $info[]=[
                    'cityName'=>$value
                ];
            }
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $info,
                'success' => true,
                'code' => '200'
            );
            \yii::$app->end(json_encode($result));
        }
    }
    /**
     * 验证用户名
     */
    public function actionCheckUsername() {
        $error = array();
        $username = isset($_POST['username']) ? $_POST['username'] : $error = array('用户名不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => ['用户名不能为空'],
                'code' => '601'
            );
        } else {
            $name = TBaseUser::find()->where(['username' => $username, 'del_flag' => 0])->one();
            if ($name) {
                $result = array(
                    "msg" => "用户名已存在",
                    "ver" => "1.5.0",
                    'data' => ['用户名已存在'],
                    'success' => false,
                    'code' => '400'
                );
            } else {
                $result = array(
                    "msg" => "",
                    "ver" => "1.5.0",
                    'data' => ['用户名可用'],
                    'success' => true,
                    'code' => '200'
                );
            }
        }
        Yii::$app->end(json_encode($result));
    }
    /**
     * 验证手机号
     */
    public function actionCheckPhone() {
        $error = array();
        $phone = isset($_POST['phone']) ? $_POST['phone'] : $error = array('手机号不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "缺少参数",
                "ver" => "1.5.0",
                'data' => $error,
                'code' => '601'
            );
        } else {
            $userProfile = TBaseUserProfile::find()->where(['mobilephone' => $phone, 'del_flag' => 0])->one();
            if ($userProfile) {
                $result = array(
                    "msg" => "该手机号已注册",
                    "ver" => "1.5.0",
                    'data' => ['该手机号已注册'],
                    'success' => false,
                    'code' => '400'
                );
            } else {
                $result = array(
                    "msg" => "'手机号可用'",
                    "ver" => "1.5.0",
                    'data' => ['手机号可用'],
                    'success' => true,
                    'code' => '200'
                );
            }
        }
        Yii::$app->end(json_encode($result));
    }
    /*
 * 微信小程序：完善信息上传头像
 * 2020/01/06
 * gyq
 */
    public function actionAppHeadImagesInput(){
        if(!empty($_FILES)){
            $path = 'files'.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.date("Ym").DIRECTORY_SEPARATOR;
            if(!is_dir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path)){
                mkdir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path, 0777, true);
            }
            $fileformat =  substr($_FILES['files']["name"], strrpos($_FILES['files']["name"], '.')+1);
            $uri = $path.md5($_FILES['files']["name"]. time()).'.'.$fileformat;
            if(move_uploaded_file($_FILES['files']["tmp_name"],\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri)){
                $result = array(
                    "msg"=> "保存成功",
                    "ver"=> "1.5.0",
                    'data'=>\Yii::$app->params['fileUrlWeiXin'].$uri,
                    'success' => true,
                    'code'=>'200'
                );
            }else{
                $result = array(
                    "msg"=> "保存失败",
                    "ver"=> "1.5.0",
                    'data'=>array(),
                    'success' => false,
                    'code'=>'400'
                );
            }
        }else{
            $result = array(
                "msg"=> "缺少参数",
                "ver"=> "1.5.0",
                'data'=>array(),
                'success' => false,
                'code'=>'601'
            );
        }
        Yii::$app->end(json_encode($result));
    }
/*
 * 微信小程序：联盟基础版与高级授权
 * 2020/02/18
 * gyq
 */
    public function actionProjectAccessManagement(){
            //查询联盟是否高级授权
            $projectId = isset($_REQUEST['projectId'])&&!empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] :6;
            $sql="select access from t_base_project where del_flag=0 and id=:projectId";
            $access=\yii::$app->db->createCommand($sql)->bindValues([':projectId'=>$projectId])->queryScalar();
            if($access=='yesOrNo.yes'){
                    //已经高级授权
                    $result = array(
                        "msg" => "高级授权",
                        "ver" => "1.5.0",
                        'data' => ['高级授权'],
                        'success' => true,
                        'code' => '200'
                    );
            }else{
                    //联盟只初级授权
                    $result = array(
                        "msg" => "基础授权",
                        "ver" => "1.5.0",
                        'data' =>['基础授权'],
                        'success' => true,
                        'code' => '200'
                    );
            }
        \yii::$app->end(json_encode($result));
    }
}
?>